package com.link2room.aeriabots.facade.impl;

import com.link2room.aeriabots.constant.CallBackType;
import com.link2room.aeriabots.dto.callBack.WxCallBackDto;
import com.link2room.aeriabots.facade.IWxCallBackFacadeService;
import com.link2room.common.exception.SysException;
import com.link2room.common.util.LogUtil;
import com.link2room.common.util.StringUtil;
import com.link2room.common.util.XmlUtil;
import com.link2room.enums.exception.AeriabotsSysExceptionEnum;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.tencent.client.ComponentClient;
import com.tencent.client.OfficialAccountClient;
import com.tencent.protocol.component.query_auth_protocol.QueryAuthResData;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by LN on 2017/5/2.
 */
@Component("wxCallBackWechatPublishFcadeService")
public class WxCallBackWechatPublishFcadeServiceImpl extends WxCallBackFacadeServiceImpl implements IWxCallBackFacadeService {
    /**
     * 微信通知处理
     *
     * @param xmlStr
     * @throws Exception
     */
    @Override
    public String wxCallBackHandller(String xmlStr) throws Exception {
        String replayStr = null;
        String resStr = null;
        WxCallBackDto dto = XmlUtil.fromXML(xmlStr, WxCallBackDto.class);
        WxCallBackDto replayDto = new WxCallBackDto();
        if(CallBackType.MSG_TYPE.EVENT.equals(dto.getMsgType())){
            String event = dto.getEvent();
            replayDto.setContent(event+"from_callback");
            replayDto.setMsgType("text");
        }else if(CallBackType.MSG_TYPE.TEXT.equals(dto.getMsgType())){
            String content = dto.getContent();
            System.out.printf(content);
            if("TESTCOMPONENT_MSG_TYPE_TEXT".equals(content)){
                replayDto.setContent("TESTCOMPONENT_MSG_TYPE_TEXT_callback");
                replayDto.setMsgType("text");
            }else if(content.contains("QUERY_AUTH_CODE")){
                String authCode = content.split(":")[1];

                QueryAuthResData res = ComponentClient.requestAuthorToken(getComponentAppid(), getComponentAccessToken(),authCode);
                if(StringUtil.isBlank(res.getErrmsg())){
                    String token = res.getAuthorization_info().getAuthorizer_access_token();
                    OfficialAccountClient.customSendText(token, dto.getFromUserName(),authCode+"_from_api");
                    replayDto.setContent("");
                    replayDto.setMsgType("text");
                }else{
                    throw new SysException(AeriabotsSysExceptionEnum.WX_SDK_ERROR,res.getErrmsg());
                }
            }
        }

        replayDto.setCreateTime(new Long(new Date().getTime()).toString().substring(0,8));
        replayDto.setToUserName(dto.getFromUserName());
        replayDto.setFromUserName(dto.getToUserName());
        WxCallBackDto resDto = null;
        replayStr = XmlUtil.toXML(replayDto);
        String time = replayDto.getCreateTime();
        WXBizMsgCrypt.EncryptBody ncryptBody= this.wxBizMsgCryptEncryptBody(replayStr, time, "nonc");
        resDto = new WxCallBackDto();
        resDto.setEncrypt(ncryptBody.getEncryptMsg());
        resDto.setNonce(ncryptBody.getNonce());
        resDto.setTimestamp(ncryptBody.getTimeStamp());
        resDto.setMsgSignature(ncryptBody.getSignature());
        resStr=ncryptBody.getEncryptMsg();
        LogUtil.logger.debug(resStr);
        return resStr;
    }
}
